<template>
    <div class="dhzn_shops">
        <div class="d_s-list">
            <div class="d_s-l-content">
                <!-- 查询 -->
                <div class="d_s-l-c-inquire">

                    <el-form label-width="70px" :model="formdata" :inline="true">
                        <el-form-item label="商家ID">
                            <el-input placeholder="请输入商家ID进行查找" v-model="formdata.id" clearable></el-input>
                        </el-form-item>

                        <el-form-item label="商家名称">
                            <el-input placeholder="请输入商家名称进行查找" v-model="formdata.name" clearable></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button @click="searchshops">搜索</el-button>
                        </el-form-item>

                    </el-form>
                </div>
                <!-- 数据列表 -->
                <div class="d_s-l-c-list">
                    
                    <p class="bb1 p10 f14">分页列表</p>

                    <div class="p10">
                        <div class="d_slcl-btn">
                            <button type="button" class="bc4a mb10 p5 wh f14 br5" @click="dialogvisile = true">添加分类</button><!-- addshops -->
                        </div>
                        <table class="d_slcl-table">
                            <thead>
                                <tr>
                                    <th>商家ID</th>
                                    <th>头像<br/><span class="n f12 ff53">(*点击查看大图)</span></th>
                                    <th>店铺名称</th>
                                    <th>商家介绍</th>
                                    <th>操作</th>
                                </tr>
                            </thead>

                            <tbody>
                                <tr v-for="(item,key) in shopslist" :key="key">
                                    <td>{{item.id}}</td>
                                    <td>
                                        <el-popover popper-class="d_slcl-t-popover" placement="top" trigger="click" v-model="item.visible">
                                            <img :src="item.logo" alt="">
                                            <img :src="item.logo" alt="" slot="reference">
                                        </el-popover>
                                    </td>
                                    <td>{{item.name}}</td>
                                    <td class="d_slcl-tbodytr"><p>{{item.descri}}</p></td>
                                    <td>
                                        <button type="button" @click="updatashops(item,key)" class="bc4a wh pt5 pr10 pb5 pl10 br5 f16">修改</button>
                                        <button type="button" @click="deleteshops(item.id,key)" class="bcfd wh pt5 pr10 pb5 pl10 br5 f16">删除</button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- 分页 -->
                <div class="d_s-l-c-paging">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

            </div>
        </div>

        <el-dialog title="添加商户" :visible.sync="dialogvisile" width="40%" top="100px" center>
            <el-form label-width="70px">
                <el-form-item v-for="(item,key) in shopsadd" :key="key" :label="item.name">
                    <el-input :type="item.type" v-model="item.value" clearable :placeholder="item.placehoder"></el-input>
                    <div v-if="key===1 && item.value !== ''" class="dialog-img"><span>商家图片预览:</span>
                        <el-popover popper-class="d_slcl-t-popover" placement="right" trigger="hover" v-model="visible">
                            <img :src="item.value" alt="">
                            <img :src="item.value" alt="" slot="reference">
                        </el-popover>
                    </div>
                    <div></div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogvisile = false">取 消</el-button>
                <el-button type="primary" @click="updataadd">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
const axios = require('axios');
export default {
    components: {},
    data() {
        return {
            formdata:{
                id: '',
                name: ''
            },
            shopsadd:[
                {name:'商家名称',value:'',placeholder:'请输入需要添加的商户名称',type:''},
                {name:'商家头像',value:'',placeholder:'请输入需要添加的商户名称',type:''},
                {name:'商家介绍',value:'',placeholder:'请输入需要添加的商户名称',type:'textarea'},
            ],
            visible: false,
            shopslist:[],
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            interval: null,                            //定时器
            dialogvisile: false,                 //弹出层的状态
            amendstate: false                   //修改的状态，用于在修改的点击函数中直接做请求，不用在弹出层内的点击函数做请求，一个函数中多个请求看的不舒服
        };
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            this.goodslist()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            const that = this;
            that.currentPage = val;
            that.goodslist()
            // if(that.paging === 1){
            //     that.classifylatt()
            // }else if(that.paging === 2){
            //     that.lookson()
            // }else if(that.paging === 3){
            //     that.inquire()
            // }else{
            //     that.updataclassify()
            // }
        },

		// token定时更新
		updatetoken(){
            // var i=0,that = this;
            // // var interval
            // // that.segregate(interval,i)
            // // console.log("函数不运行")
            // // console.log(interval)
            // // console.log(interval)
            // that.interval = setInterval(() => {
            //     setTimeout(()=>{
            //         if(that.interval <that.interval){
            //             console.log('看到吃屎')
            //         }
            //         // console.log('第'+that.interval+'定时器',i+=1)
            //     },0)
            // }, 1000)
            // // if(that.interval != null){
            // //     console.log(`停止之前的值： ${that.interval}`)
            // //     clearInterval(that.interval);
            // // }
            // // clearInterval(time);
            // console.log("区分定时器",that.interval)
            // // console.log(that.interval)
            

            // // if(this.token !== ''){
            //         //     const axios = require('axios');
            //         //     let data = {username: 'dhzn', password: 'dhzn'}
            //         //     let updata = JSON.stringify(data);
            //         //     axios({
            //         //         method: 'post',
            //         //         url: '/api/getAuthority/manager',
            //         //         headers: {'Content-Type': 'application/json'},
            //         //         data: updata
            //         //     })
            //         //     .then( resp=> {console.log(resp.data.data,"定时更新")})
            //         //     .catch( err=> {console.log(err,"定时更新")})
            //         // }
        },
        
        // 请求商家信息
        requestshops(){
            let that = this;
            let data = {current: that.currentPage, size: that.pagesize};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/business/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.shopslist = resp.data.data
                that.total = resp.data.code;
                if(that.shopslist === undefined){
                    sessionStorage.removeItem("token")
                    location.reload()
                }else{
                    for(var u=0;u<that.shopslist.length;u++){
                        that.shopslist[u].visible = false;
                    }
                }                 
            })
            .catch( err=> {console.log(err)})
        },

        //添加商家
        addshops(){},
        
        // 弹出层关闭的回调
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        },

        // 删除的方法
        deleteshops(detid,detkey){
            let that = this;
            let data = {id:detid};
            let updata = JSON.stringify(data);
            that.$confirm('商家删除后无法找回相应数据',"警告",{
                confirmButtinText: '确定',
                cancelButtinText: '取消',
                center: 'true',
                type: 'warning'
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/business/delete',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                })
                .then( resp=> {
                    console.log(resp)
                    that.shopslist.splice(detkey,1)
                })
                .catch( err=> {console.log(err)})
                that.$message({
                    type: 'success',
                    message: '删除成功！'
                });
            }).catch(()=>{
                that.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 弹出层添加商户的方法
        updataadd(){
            let that = this;
            // let data = {name:that.shopsadd[0].value, logo:that.shopsadd[1].value, descri:that.shopsadd[2].value};
            // let updata = JSON.stringify(data)
            if(that.shopsadd[0].value === ''){
                this.$message.error('商家名称不能为空');
            }else if(that.shopsadd[1].value === ''){
                this.$message.error('商家头像不能为空');
            }else if(that.shopsadd[2].value === ''){
                this.$message.error('商家介绍不能为空');
            }else{
                let data = {name:that.shopsadd[0].value, logo:that.shopsadd[1].value, descri:that.shopsadd[2].value};
                let updata

                // 修改商户数据
                if(that.amendstate){           
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        that.dialogvisile = false;
                        that.amendstate = false;
                        data.id = that.shopsadd[0].id;
                        updata = JSON.stringify(data)
                        axios({
                            method: 'post',
                            url: '/api/business/update',
                            headers: {
                                'Content-Type': 'application/json',
                                'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                            },
                            data: updata
                        })
                        .then( resp=> {
                            console.log(resp)
                            that.shopslist.splice(that.shopsadd[0].key,1,data)
                            that.dialogvisile = false;
                            that.shopsadd.array.forEach(element => {
                                element.value = ''
                            });
                        })
                        .catch( err=> {console.log(err)})
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });          
                    });
                }else{
                    // 添加商户
                    updata = JSON.stringify(data)
                    axios({
                        method: 'post',
                        url: '/api/business/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    })
                    .then( resp=> {
                        // console.log(resp)
                        that.shopslist.push(data)
                        that.dialogvisile = false;
                        that.shopsadd.array.forEach(element => {
                            element.value = ''
                        });
                    })
                    .catch( err=> {console.log(err)})
                }
            }   
        },

        // 搜索查询
        searchshops(){
            let that = this;
            let data = {
                current: that.currentPage, 
                size: that.pagesize,
                id: that.formdata.id,
                name: that.formdata.name
            };
            for(var i in data)
                if(data[i] === ''){
                    delete data[i]
                }
            let updata = JSON.stringify(data);
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/business/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.shopslist = resp.data.data
                that.total = resp.data.code;
            })
            .catch( err=> {console.log(err)})
        },

        // 修改
        updatashops(item,key){
            let that = this;
                that.dialogvisile = true;
                that.amendstate = true;
                that.shopsadd[0].value = item.name;
                that.shopsadd[0].key = key;
                that.shopsadd[0].id = item.id;
                that.shopsadd[1].value = item.logo;
                that.shopsadd[2].value = item.descri;
            // }
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                // that.updatetoken()
                that.requestshops()
			}).catch( err=> {})
        }
    },
    created() {
        // consoel.log(2)
    },
    mounted() {
        let that = this;
        that.newtoken()
        // consoel.log(3)
    },
    beforeCreate() {
        // consoel.log(1)
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {
        clearInterval(this.timer); 
        this.timer = null;
    },
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
    .dhzn_shops{
        height: calc(100% - 56px);
        box-sizing: border-box;
    }
    .d_s-list{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        /* background-color: #ffffff; */
    }
    /* .d_s-l-table{
        text-align: center;
        background-color: #ffffff;
        border-collapse: collapse;
    }
    .d_s-l-table>tr:nth-child(even){
        background-color: #b4b4b4;
        color: white;
    }
    .d_s-l-table>tr>th,.d_s-l-table>tr>td{
        height: 50px;
    } */
    /* 查询 */
    .d_s-l-c-inquire{
        padding-top: 22px;
        background-color: #ffffff;
    }

    /* 商家列表 */
    .d_s-l-c-list{
        margin-top: 10px;
        background-color: #ffffff;
    }
    .d_slcl-table{
        text-align: center;
        width: 100%;
        /* margin: 10px; */
        color: #666666;
        border-bottom: 1px solid #e0e0e0;
        border-left: 1px solid #e0e0e0;
        border-collapse: collapse;
    }
    .d_slcl-table thead tr,.d_slcl-table tbody tr:hover{
        background-color: #F2F2F2;
    }
    .d_slcl-table th, .d_slcl-table td{
        max-width: 300px;
        min-height: 50px;
        padding: 10px;
        border-top: 1px solid #e0e0e0;
        border-right: 1px solid #e0e0e0;
        /* overflow : hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical; */
    }
    /* 商家列表的图片大小 */
    .d_slcl-table td img{
        max-width: 120px;
        max-height: 80px;
    }
    .d_slcl-t-popover img{
        max-width: 500px;
        max-width: 500px;;
    }

    /* 商家介绍的单独定一下 */
    .d_slcl-tbodytr p{
        text-align: left;
        overflow:hidden; 
        text-indent: 2em;
        text-overflow:ellipsis;
        display:-webkit-box;
        /* autoprefixer: off */
        -webkit-box-orient:vertical;
        /* autoprefixer: on */
        -webkit-line-clamp:4; 
    }

    /* 弹出层内的图片预览 */
    .dialog-img{
        height: 60px;
        font-size: 12px;
    }
    .dialog-img img{
        vertical-align: text-top;
        max-width: 80%;
        max-height: 80%;
    }
</style>